<template>
    <div class="container">
        <h3>exceljs</h3>
        <el-button type="primary" @click="exportToExcel">导出Excel</el-button>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="时间" width="180" />
            <el-table-column prop="name" label="名称" width="180" />
            <el-table-column prop="address" label="地址" />
            <el-table-column prop="imgs" label="图片">
                <template #default="scope">
                    <img :src="scope.row.image" width="50" height="50" alt="" />
                </template>
            </el-table-column>
        </el-table>
        <hr />
        <h3>js-table2excel</h3>
        <demo1></demo1>
    </div>
</template>

<script setup>
    import demo1 from "./demo1.vue";
    import { ref } from "vue";
    import ExcelJS from "exceljs";

    const tableData = ref([
        {
            date: "2016-05-03",
            name: "Tom",
            image: "https://img0.baidu.com/it/u=2227428711,1104760943&fm=253&fmt=auto&app=138&f=JPEG?w=240&h=160",
            address: "No. 189, Grove St, Los Angeles",
        },
        {
            date: "2016-05-02",
            name: "Tom",
            image: "https://img0.baidu.com/it/u=2227428711,1104760943&fm=253&fmt=auto&app=138&f=JPEG?w=240&h=160",
            address: "No. 189, Grove St, Los Angeles",
        },
        {
            date: "2016-05-04",
            name: "Tom",
            image: "https://img0.baidu.com/it/u=2227428711,1104760943&fm=253&fmt=auto&app=138&f=JPEG?w=240&h=160",
            address: "No. 189, Grove St, Los Angeles",
        },
        {
            date: "2016-05-01",
            name: "Tom",
            image: "https://img0.baidu.com/it/u=2227428711,1104760943&fm=253&fmt=auto&app=138&f=JPEG?w=240&h=160",
            address: "No. 189, Grove St, Los Angeles",
        },
    ]);
    function fileToBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });
    }
    const exportToExcel = async () => {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet("Sheet1");
        // 添加一些文本或数据
        // worksheet.getCell("A1").value = "这是包含图片的单元格";
        worksheet.columns = [
            { header: "时间", key: "date", width: 100 },
            { header: "名称", key: "name", width: 100 },
            { header: "地址", key: "address", width: 100 },
            { header: "图片", key: "image", width: 100 },
        ];
        for (const [index, row] of tableData.value.entries()) {
            worksheet.addRow([row.data, row.name, row.address, ""]);

            // 将图片转换为 Base64
            const image = new Image();
            image.setAttribute("crossOrigin", "anonymous");
            image.src = row.image;

            try {
                await new Promise((resolve) => {
                    image.onload = () => {
                        const canvas = document.createElement("canvas");
                        const ctx = canvas.getContext("2d");
                        canvas.width = image.width;
                        canvas.height = image.height;
                        ctx.drawImage(image, 0, 0);

                        // 将图片转换为 Base64 编码
                        const base64Image = canvas.toDataURL();

                        // 将 Base64 编码的图片插入 Excel 文件
                        worksheet.addImage(
                            {
                                base64: base64Image,
                                extension: "png",
                            },
                            {
                                tl: { col: 3, row: index + 2 }, // 图片插入的位置（列为第2列，行为当前行）
                                ext: { width: 50, height: 50 },
                            }
                        );
                        resolve();
                    };
                });
            } catch (error) {
                console.error(error);
            }
        }

        // 导出文件
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = URL.createObjectURL(blob);
        // 创建并点击a标签触发下载
        const link = document.createElement("a");
        link.href = url;
        link.download = "FileName.xlsx";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        // 添加表格标题
        // const headerRow = worksheet.addRow(["时间", "名称", "地址", "图片"]);
        // headerRow.font = { bold: true };
        // // 添加表格数据
        // tableData.value.forEach((row, rowIndex) => {
        //     const newRow = worksheet.addRow([row.name, "", row.value]); // 图片列留空，稍后插入图片

        //     // 插入图片
        //     worksheet.addImage(
        //         {
        //             filename: row.imageUrl,
        //             extension: "png",
        //         },
        //         {
        //             tl: { col: 1, row: rowIndex + 2 }, // 图片插入的位置（列为第2列，行为当前行）
        //             ext: { width: 50, height: 50 },
        //         }
        //     );
        // });

        // // 保存为 Excel 文件
        // const buffer = await workbook.writeBuffer();
        // const blob = new Blob([buffer], {
        //     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        // });
        // const downloadUrl = URL.createObjectURL(blob);

        // const a = document.createElement("a");
        // a.href = downloadUrl;
        // a.download = "FileName.xlsx";
        // document.body.appendChild(a);
        // a.click();
        // document.body.removeChild(a);
        // URL.revokeObjectURL(downloadUrl);

        // // 添加表格标题
        // worksheet.addRow(["时间", "名称", "地址", "图片"]);

        // // 添加表格数据
        // tableData.value.forEach((row, rowIndex) => {
        //     // const newRow = worksheet.addRow([row.name, "图片", row.value]);

        //     // 插入图片
        //     ExcelJS.loadImage(row.image, function (err, image) {
        //         if (err) {
        //             console.error(err);
        //         } else {
        //             // 将图片插入到当前行的第二列（从0开始）
        //             worksheet.addImage(image, {
        //                 tl: { col: 1, row: rowIndex + 1 },
        //                 ext: { width: 50, height: 50 },
        //             });
        //         }
        //     });
        // });

        // // 保存为 Excel 文件
        // workbook.write("FileName.xlsx");
    };
</script>
<style lang="less" scoped>
    .container {
    }
</style>
